package com.ztesoft.book.core.quartz.schedulejob.util;

import cn.hutool.extra.spring.SpringUtil;
import com.ztesoft.book.core.quartz.schedulejob.dto.ScheduleJobDTO;
import com.ztesoft.book.core.quartz.schedulejoblog.dto.ScheduleJobLogDTO;
import com.ztesoft.book.core.quartz.schedulejoblog.service.ScheduleJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.time.LocalDateTime;


/**
 * @Description: 定时任务Bean，继承QuartzJobBean
 * @Author: YangFan
 * @Date: 2021-03-19 17:07
 */
@Slf4j
public class ScheduleJobBean extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJobDTO scheduleJobDto = (ScheduleJobDTO) context.getMergedJobDataMap()
                .get(ScheduleJobDTO.JOB_PARAM_KEY);

        //获取spring bean
        ScheduleJobLogService scheduleJobLogService = SpringUtil.getBean("scheduleJobLogService");

        //数据库保存执行记录
        ScheduleJobLogDTO scheduleJobLogDto = new ScheduleJobLogDTO();
        scheduleJobLogDto.setJobId(scheduleJobDto.getId());
        scheduleJobLogDto.setBeanName(scheduleJobDto.getBeanName());
        scheduleJobLogDto.setParams(scheduleJobDto.getParams());
        scheduleJobLogDto.setCreateTime(LocalDateTime.now());
        scheduleJobLogDto.setUpdateTime(LocalDateTime.now());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            log.info("【定时任务准备执行】 | 任务ID：" + scheduleJobDto.getId() + " | 任务描述：" + scheduleJobDto.getRemark() + " | ");

            Object target = SpringUtil.getBean(scheduleJobDto.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", String.class, String.class);
            method.invoke(target, scheduleJobDto.getParams(), scheduleJobDto.getFunParams());

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            scheduleJobLogDto.setTimes((int) times);
            //任务状态    0：成功    1：失败
            scheduleJobLogDto.setStatus(0);

            log.info("【定时任务执行完毕】 | 任务ID：" + scheduleJobDto.getId() + " | 总共耗时：" + times + "毫秒 | ");
        }
        catch (Exception e) {
            log.info("【定时任务执行失败】 | 任务ID：" + scheduleJobDto.getId(), e + " | ");

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            scheduleJobLogDto.setTimes((int) times);

            //任务状态    0：成功    1：失败
            scheduleJobLogDto.setStatus(1);
            scheduleJobLogDto.setError(StringUtils.substring(e.toString(), 0, 2000));
        }
        finally {
            scheduleJobLogService.save(scheduleJobLogDto);
        }
    }
}
